//
//  AddWorkPersonViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/11/4.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "AddWorkPersonViewController.h"
#import "CenterLabelTableViewCell.h"
#import "DutyBasicTableViewCell.h"
#import "ReasonTextTableViewCell.h"
#import "DatePickerView.h"

#import "DepartPersonListView.h"

#define getDepartPersonList @"getDepartPersonList"//获取委托人列表
#define SELECTPERSONTEXT @"点击选择委托人"
#define REASONTEXT @"请输入受托内容~"

@interface AddWorkPersonViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    DatePickerView *_datePickerView;//时间选择框
    NSMutableArray *_messageArr;//内容数组
    UITapGestureRecognizer *_tapGesture;//手势
}
@property (nonatomic,strong) UILabel *selectPersonLabel;//选择委托人
@property (nonatomic,strong) UITableView *tableView;//列表
@property (nonatomic,strong) UIButton *addPersonButton;//选择委托人
@property (nonatomic,strong) UITextView *reasonTextView;//文本输入框
@property (nonatomic,strong) DepartPersonListModel *personListModel;
//@property (nonatomic,strong) DepartPersonListView *departPersonView;
@end
@implementation AddWorkPersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [self setNavigationTitle:@"工作委托"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(datePickViewCancel:) name:@"datePickViewCancel" object:nil];
    [self setLeftBackNavigation];
    [self creatView];
    [self getDepartPersonListRequest];
    // Do any additional setup after loading the view.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

#pragma mark -键盘弹出的通知事件
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    _tableView.height=IPHONE_HEIGHT-64-height;
    [self addTapGestureRecognizerWithView:_tableView];
    // CGFloat width = keyboardRect.size.width;
    
}

#pragma mark -键盘退出的通知事件
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    //    //获取键盘高度
    //    NSDictionary *userInfo = [aNotification userInfo];
    //    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    //    CGRect keyboardRect = [aValue CGRectValue];
    //    CGFloat height = keyboardRect.size.height;
    
    //    [UIView animateWithDuration:0.3 animations:^{
    //        _backMsgView.y=IPHONE_HEIGHT-51;
    //    }];
    [self removeTapGestureRecognizerWithView:_tableView];
    _tableView.height=IPHONE_HEIGHT-64;
    //_tableView.y=64;
    
}

#pragma mark -手势的响应事件
- (void)tapGestureClick{
    [_reasonTextView resignFirstResponder];
}

#pragma mark -时间选择取消的通知事件
- (void)datePickViewCancel:(NSNotification *)notification{
    if (_datePickerView) {
        [_datePickerView removeFromSuperview];
        _datePickerView=nil;
    }
}

#pragma mark — creatView
- (void)creatView{
    _messageArr=[NSMutableArray arrayWithArray:@[@"",_beginStr,_endStr]];
    //创建列表
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-64) style:UITableViewStyleGrouped];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    _tableView.bounces=NO;
    //[self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_tableView];
    
    //添加提交和存草稿button
    UIView *footView=[[UIView alloc]initWithFrame:CGRectMake(0, 20, IPHONE_WIDTH, 60)];
    footView.backgroundColor=[UIColor clearColor];
    
    UIButton *submitButton=[MyControl creatButtonWithFrame:CGRectMake(10,20, IPHONE_WIDTH-20, 40) target:self sel:@selector(submitClick) tag:120 image:nil title:@"确认委托"];
    submitButton.layer.masksToBounds=YES;
    submitButton.layer.cornerRadius=5;
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitButton.backgroundColor=COLOR_MIDBLUE;
    [footView addSubview:submitButton];
    _tableView.tableFooterView=footView;
    //    DatePickerView *date=[[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    //    [[[UIApplication sharedApplication].delegate window] addSubview:date];
}

- (void)submitClick{
    [_reasonTextView resignFirstResponder];
    if ([_selectPersonLabel.text isEqualToString:SELECTPERSONTEXT]) {
        [LZXHelper postMessageWithText:@"请选择委托人!" View:self.view];
        return;
    }
    if ([_reasonTextView.text isEqualToString:REASONTEXT]) {
        [LZXHelper postMessageWithText:@"委托内容不能为空!" View:self.view];
        return;
    }
    if (![self compareOneTime:_beginStr withAnotherTime:_endStr]) {
        [LZXHelper postMessageWithText:@"请假结束时间应该在请假开始时间之后!" View:self.view];
        return;
    }
    NSString *personId=@"";
    for (DepartPersonListModel *model in _personListModel.dataArr) {
        if ([model.personName isEqualToString:_selectPersonLabel.text]) {
            personId=model.personId;
            break;
        }
    }
    
    DepartPersonListModel *model=[DepartPersonListModel new];
    model.personName=[_selectPersonLabel.text copy];
    model.beginStr=[_beginStr copy];
    model.endStr=[_endStr copy];
    model.personId=[personId copy];
    model.msgContent=[_reasonTextView.text copy];
    if (_myBlock) {
        _myBlock(model);
    }
    [self backClick];
}
#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==1) {
        return _messageArr.count;
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        NSString *cellID=@"CenterLabelTableViewCell";
        CenterLabelTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell=[[CenterLabelTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        cell.myTitle.text=SELECTPERSONTEXT;
        _selectPersonLabel=cell.myTitle;
        return cell;
    }else{
        if (indexPath.row==1||indexPath.row==2) {
            NSString *cellID=@"DutyBasicTableViewCell";
            DutyBasicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell=[[DutyBasicTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
            }
            if (indexPath.row==1) {
                cell.myTitleLabel.text=@"开始时间 :";
            }else{
                cell.myTitleLabel.text=@"结束时间 :";
            }
            cell.messageLabel.text=_messageArr[indexPath.row];
            cell.messageLabel.textColor=[UIColor blackColor];
            cell.arrowImageView.hidden=NO;
            return cell;

        }else{
            NSString *cellID=@"ReasonTextTableViewCell";
            ReasonTextTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell=[[ReasonTextTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID title:nil noticeStr:REASONTEXT];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
            }
            _reasonTextView=cell.reasonTextView;
            //cell.reasonTextView.delegate=self;
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        if (indexPath.row==1||indexPath.row==2){
            [_reasonTextView resignFirstResponder];
            _datePickerView=[[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
            __weak NSMutableArray *myMessageArr=_messageArr;
            __weak UITableView *myTableView=_tableView;
            __weak AddWorkPersonViewController *mySelf=self;
            _datePickerView.sureBlock=^(NSString *timeStr){
                if (indexPath.row==1) {
                    //如果是选择开始时间
                    //先判断有没有结束时间,如果有要进行比对
//                    if (mySelf.endStr) {
//                        if (![mySelf compareOneTime:mySelf.beginStr withAnotherTime:mySelf.endStr]) {
//                            [LZXHelper postMessageWithText:@"请假结束时间应该在请假开始时间之后!" View:mySelf.view];
//                        }
//                    }
//                    if (_dutyType==ApplyHoliday) {
//                        //如果是请假
//                        if ([mySelf compareTime:timeStr]) {
//                            //比现在的时间早
//                            [LZXHelper postAlertViewControllerWithTitle:@"您选择的请假开始时间早于今天,要补假吗?" message:nil cancelButtonTitle:@"选错时间了" otherButtonTitle:@"去补假" cancelEvent:^{
//                                
//                            } otherEvent:^{
//                                _dutyType=1;
//                                
//                            } viewController:mySelf];
//                        }else{
//                            //比现在的时间晚
                            mySelf.beginStr=[timeStr copy];
                            [myMessageArr replaceObjectAtIndex:indexPath.row withObject:timeStr];
                            [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//                        }
                        
//                   }else{
                        //如果是补假
//                        if ([mySelf compareTime:timeStr]){
                            //比现在的时间早
//                            mySelf.beginStr=[timeStr copy];
//                            [myMessageArr replaceObjectAtIndex:indexPath.row withObject:timeStr];
//                            [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//                        }else{
//                            //比现在的时间晚
//                            [LZXHelper postAlertViewControllerWithTitle:@"您选择的请假开始时间晚于今天,要请假吗?" message:nil cancelButtonTitle:@"选错时间了" otherButtonTitle:@"去请假" cancelEvent:^{
//                                
//                            } otherEvent:^{
//                                _dutyType=0;
//                            } viewController:mySelf];
//                        }
//                    }
                    
                }else{
                    //点击结束时间
                    mySelf.endStr=[timeStr copy];
                    [myMessageArr replaceObjectAtIndex:indexPath.row withObject:timeStr];
                    [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                }
            };
            [[[UIApplication sharedApplication].delegate window] addSubview:_datePickerView];
        }
    }else if (indexPath.section==0){
        if (_personListModel) {
                NSMutableArray *titleArr=[NSMutableArray new];
                [titleArr addObject:SELECTPERSONTEXT];
                for (DepartPersonListModel *model in _personListModel.dataArr) {
                    [titleArr addObject:model.personName];
                }
                DepartPersonListView *departPersonView=[[DepartPersonListView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT) titleArr:titleArr];
                __weak AddWorkPersonViewController *mySelf=self;
                departPersonView.myBlock=^(NSString *departName){
                    mySelf.selectPersonLabel.text=departName;
                };
                [[[UIApplication sharedApplication].delegate window] addSubview:departPersonView];
        }else{
            [self getDepartPersonListRequest];
        }
    }else{
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1&&indexPath.row==0) {
        return 80;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

//#pragma mark -textViewDelegate
//
//- (void)textViewDidBeginEditing:(UITextView *)textView{
//    NSIndexPath* path = [NSIndexPath indexPathForRow:3 inSection:1];
//    [self performSelector:@selector(scrollToCell:) withObject:path afterDelay:0.5f];
//}
//
//-(void) scrollToCell:(NSIndexPath*) path {
//    [_tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionNone animated:YES];
//}
//
//
//- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
//    return YES;
//}

#pragma mark -获取人员列表请求

- (void)getDepartPersonListRequest{
    NSDictionary *dict=@{
                         @"departName":[LZXHelper getUserDepartName]?[LZXHelper getUserDepartName]:@"",
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    //[LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getDepartPersonList soapBody:soap success:^(id responseObject) {
        //[LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        _personListModel=[[DepartPersonListModel alloc]initWithResponse:responseObject];
        if ([_personListModel.code isEqualToString:@"200"]) {
            
            
        }else if([_personListModel.code isEqualToString:@"220"]){
            //[LZXHelper postMessageWithText:_model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        //[LZXHelper hideLoadViewWithView:self.view];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
